let watermark; //水印元素

const destoryWatermark = () => {
	if (watermark) {
		document.body.removeChild(watermark)
		watermark = null
	}
}

// 创建水印
const createWatermark = (config = {}, fillText) => {
	let size = 150 //水印间隙 值越大水印数量越少
	if (fillText.length > 15) {
		size = fillText.length * 10
	}
	const canvas = document.createElement('canvas') //创建canvas，用于生成base64图片充当水印
	const ctx = canvas.getContext('2d')
	canvas.width = size
	canvas.height = size
	ctx.translate(size / 2, size / 2)
	ctx.rotate((Math.PI / 180) * -45)
	ctx.font = '18px serif'
	ctx.fontWeight = 'bold'
	ctx.textAlign = "center"
	ctx.textBaseline = "middle"
	ctx.fillStyle = 'rgba(0, 0, 0, .2)'

	ctx.fillText(fillText, 0, 0)
	const base64 = canvas.toDataURL()

	function _generate() {
		watermark && watermark.remove()
		watermark = document.createElement('div')
		watermark.style.position = 'fixed'
		watermark.style.width = '100%'
		watermark.style.height = '100%'
		watermark.style.top = 0
		watermark.style.zIndex = 2147483647
		watermark.style.pointerEvents = 'none'

		if (config.docWatermarkType === 1) {
			watermark.style.backgroundImage = 'url(' + base64 + ')'
		} else {
			watermark.style.backgroundImage = `url(${config.docWatermarkImage})`
			watermark.style.backgroundRepeat = 'no-repeat'
			watermark.style.backgroundPosition = 'center center'
			watermark.style.backgroundSize = '100% 100%'
			watermark.style.opacity = '.2'
		}
		document.body.append(watermark)
	}
	_generate() //调用生成页面水印
	//通过MutationObserver监听元素修改，防止水印篡改
	new MutationObserver(records => {
		for (const record of records) {
			//通过F12修改Style，删除水印重新绘制
			if (record.target === watermark && config.enableDocWatermark) {
				_generate()
			}
			for (const item of record.removedNodes) {
				//通过F12删除水印元素，重新生成
				if (item === watermark && config.enableDocWatermark) {
					_generate()
				}
			}
		}
	}).observe(document.body, {
		childList: true,
		subtree: true,
		attributes: true
	})
}

export default{
	createWatermark,
	destoryWatermark
}
